package com.arcpan.component;

import com.arcpan.Constant.BaseConstant;
import com.arcpan.Entity.Dto.SysSettingDto;
import com.arcpan.Entity.Dto.UserSpaceDto;
import com.arcpan.Mapper.FileInfoMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component("RedisComponent")
public class RedisComponent {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private FileInfoMapper fileInfoMapper;

    @Resource
    private RedisUtils redisUtils;
    public SysSettingDto getsysSettingDto(){
SysSettingDto sysSettingDto= (SysSettingDto) redisUtils.get(BaseConstant.REDIS_KEY_SYS_SETTING);
if(null == sysSettingDto){
    sysSettingDto=new SysSettingDto();
    redisUtils.set(BaseConstant.REDIS_KEY_SYS_SETTING,sysSettingDto);

}
return sysSettingDto;
    }

    public void saveUserSpaceuse(String userId, UserSpaceDto userSpaceDto) {
  redisUtils.setex(BaseConstant.REDIS_KEY_USER_SPACE_USE+userId,userSpaceDto,BaseConstant.REDIS_KEY_EXPIRE_DAY);
    }
public void saveUserSpaceuse1(String userId, UserSpaceDto userSpaceDto) {
    redisUtils.set(BaseConstant.REDIS_KEY_USER_SPACE_USE+userId,userSpaceDto);
}
    public UserSpaceDto getUserSpace(String userId) {
        UserSpaceDto userSpaceDto= (UserSpaceDto) redisUtils.get(BaseConstant.REDIS_KEY_USER_SPACE_USE+userId);
        System.out.println("12334");
        if(null == userSpaceDto){
            userSpaceDto=new UserSpaceDto();
            //todo查询用户当前大小的总和
            Long userSpace=fileInfoMapper.selectUseSpace(userId);
            userSpaceDto.setUseSpace(userSpace);
            userSpaceDto.setTotalSpace(getsysSettingDto().getUserInitUserSpace()*BaseConstant.MB);
            saveUserSpaceuse(userId,userSpaceDto);
//            redisTemplate.opsForValue().set(BaseConstant.REDIS_KEY_USER_SPACE_USE+userId,userSpaceDto);
            System.out.println(userSpaceDto+"1233");
            return userSpaceDto;
        }
        return userSpaceDto;
    }

    public Long getFileTemplate(String userId, String fileId) {
        Long currentSize=getFileSizeFromRedis(BaseConstant.REDIS_KEY_USER_FILE_TEMP+userId+fileId);
        return currentSize;

    }
    public void saveFileTempSize(String userId,String fileId,Long fileSize){
        Long currentSize=getFileTemplate(userId,fileId);
        redisUtils.setex(BaseConstant.REDIS_KEY_USER_FILE_TEMP+userId+fileId,currentSize+fileSize,BaseConstant.EXPIRE_TEN);
    }

    //获取临时文件大小
    private Long getFileSizeFromRedis(String key){
        Object sizeObk=redisUtils.get(key);
        if(sizeObk == null){
            return 0L;
        }
        if(sizeObk instanceof Integer){
            return ((Integer) sizeObk).longValue();
        }else if(sizeObk instanceof  Long){
            return (Long) sizeObk;
        }
        return 0L;
    }

}
